package com.ebelter.ty.ui.fragment.scale;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ebelter.btcomlib.bases.fragment.BaseFragment;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.ty.AppConfig;
import com.ebelter.ty.R;
import com.ebelter.ty.model.http.TyNetUtil;
import com.ebelter.ty.model.http.bean.OriginalParametersResponse;
import com.ebelter.ty.ui.activity.ScaleMainActivity;
import com.ebelter.ty.utils.ScaleBaseUtils;
import com.ebelter.ty.utils.TyUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;


/**
 * 血糖
 */

public class Scale_M_B1_Fragment extends BaseFragment {


    public static final String TAG = "Scale_M_B1_Fragment";

    private TextView pager_goal_currentWeight_tv;//当前体重
    private TextView pager_goal_suggtion1_tv;//理想体重
    private EditText pager_goal_targetWeight_ed;//目标体重
    private TextView pager_goal_targetWeight_unit_tv1;//目标体重 旁边的单位lb
    private TextView pager_goal_targetWeight_unit_tv2;//目标体重 旁边的单位kg

    private TextView pager_goal_suggtion2_tv;
    private TextView pager_goal_targetWeight_tip_tv;

    private TextView pager_goal_targetWeight_set_tv;


    @Override
    protected int setLayoutResouceId() {
        return R.layout.scale_m_buttom1_goal;
    }

    @Override
    protected void initView() {
        super.initView();
        FV();
    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        updateWeight();
        updateIdealWeight();
        disTargetWeight();
        updateUnitText();

    }

    private void updateUnitText() {
        String local = AppUtils.getLocalStr();
        if (TextUtils.equals(AppUtils.iw,local)){
            if (pager_goal_targetWeight_unit_tv1!=null){
                ViewUtils.displayView(pager_goal_targetWeight_unit_tv2);
                pager_goal_targetWeight_unit_tv1.setText(AppConfig.getInstance().isKgModel()?unitKg:unitLb);
                ViewUtils.goneView(pager_goal_targetWeight_unit_tv2);
            }
        }else {
            if (pager_goal_targetWeight_unit_tv2!=null){
                ViewUtils.displayView(pager_goal_targetWeight_unit_tv1);
                pager_goal_targetWeight_unit_tv2.setText(AppConfig.getInstance().isKgModel()?unitKg:unitLb);
                ViewUtils.goneView(pager_goal_targetWeight_unit_tv1);
            }
        }
    }

    private void FV() {
        pager_goal_currentWeight_tv = mRootView.findViewById(R.id.pager_goal_currentWeight_tv);
        pager_goal_suggtion1_tv = mRootView.findViewById(R.id.pager_goal_suggtion1_tv);
        pager_goal_targetWeight_ed = mRootView.findViewById(R.id.pager_goal_targetWeight_ed);
        pager_goal_targetWeight_unit_tv2 = mRootView.findViewById(R.id.pager_goal_targetWeight_unit_tv2);
        pager_goal_suggtion2_tv = mRootView.findViewById(R.id.pager_goal_suggtion2_tv);
        pager_goal_targetWeight_set_tv = mRootView.findViewById(R.id.pager_goal_targetWeight_set_tv);
        pager_goal_targetWeight_tip_tv = mRootView.findViewById(R.id.pager_goal_targetWeight_tip_tv);
        pager_goal_targetWeight_unit_tv1 = mRootView.findViewById(R.id.pager_goal_targetWeight_unit_tv1);
        pager_goal_targetWeight_set_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBtClick();
            }
        });
    }

    private void updateIdealWeight() {

        int h = UserSpUtil.readInt(Constants.IUser.HEIGHT);//这个体重是服务器的 单位永远是kg
        ViewUtils.setTextViewStr(pager_goal_suggtion1_tv, getIdeaWeightTip(h));

    }

    private float idealWeight_min;//kg
    private float idealWeight_max;

    private String unitKg = StringUtils.getResStr(R.string.kg);
    private String unitLb = StringUtils.getResStr(R.string.lb);

    private String getIdeaWeightTip(int height) {
        float min = ScaleBaseUtils.getIdeaWeightMin(height);
        float max = ScaleBaseUtils.getIdeaWeightMax(height);

        min = NumUtils.numBaoLiuWei1(min);
        max = NumUtils.numBaoLiuWei1(max);

        idealWeight_min = min;
        idealWeight_max = max;

        String ideaWeight = StringUtils.getResStr(R.string.Your_ideal_weight_1_1);

        if (AppConfig.getInstance().isKgModel()) {

            return ScaleBaseUtils.placeHolder2(ideaWeight, ScaleBaseUtils.unitDisplay(NumUtils.numBaoLiuWei1(min) + "", unitKg), ScaleBaseUtils.unitDisplay(NumUtils.numBaoLiuWei1(max) + "", unitKg));
        } else {
            min = ScaleBaseUtils.kg2lb(min);
            max = ScaleBaseUtils.kg2lb(max);

            return ScaleBaseUtils.placeHolder2(ideaWeight, ScaleBaseUtils.unitDisplay(NumUtils.numBaoLiuWei1(min) + "", unitLb), ScaleBaseUtils.unitDisplay(NumUtils.numBaoLiuWei1(max) + "", unitLb));
        }
    }

    private void updateWeight() {
        float currentWeight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);//这个体重是服务器的 单位永远是kg
        if (currentWeight <= 0) {//如果当前体重小于零时把两个控件隐藏掉
            ViewUtils.goneView(pager_goal_targetWeight_tip_tv);
            ViewUtils.goneView(pager_goal_suggtion2_tv);
            return;
        }
        if (currentWeight < 0) {
            return;
        }
        ViewUtils.displayView(pager_goal_targetWeight_tip_tv);//带背景的按钮提示
        ViewUtils.displayView(pager_goal_suggtion2_tv);//提示文字


        String unit = AppConfig.getInstance().isKgModel() ? unitKg : unitLb;

        String cw = NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(currentWeight)) + "";
        if (TextUtils.equals(unit, unitLb)) {
            cw = ScaleBaseUtils.unitDisplay2(cw, unit);
        } else {
            cw = ScaleBaseUtils.unitDisplay(cw, unit);
        }

        ViewUtils.setTextViewStr(pager_goal_currentWeight_tv, cw);
        disWeightSuggestion2();
    }

    private void disWeightSuggestion2() {
        float currentWeight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);//这个体重是服务器的 单位永远是kg
        float targetWeight = UserSpUtil.readFloat(Constants.IUser.TARGET_WEIGHT);//这个体重是服务器的 单位永远是kg

        float c = NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(currentWeight));
        float t = NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(targetWeight));
        float differenceValue = Math.abs(c - t);

        String unit = AppConfig.getInstance().isKgModel() ? unitKg : unitLb;

        if (c == t) {
            ViewUtils.setTextViewStr(pager_goal_targetWeight_tip_tv, R.string.str_Maintain);
            ViewUtils.setTextViewStr(pager_goal_suggtion2_tv, R.string.Youre_doing_great_keep_it_up);
        } else if (c > t) {
            ViewUtils.setTextViewStr(pager_goal_targetWeight_tip_tv, R.string.str_Lose);
            ViewUtils.setTextViewStr(pager_goal_suggtion2_tv, String.format(StringUtils.getResStr(R.string.Lose_1_to_achieve_this_goal), differenceValue, unit));
        } else {
            pager_goal_targetWeight_tip_tv.setText(R.string.str_Gain);
            pager_goal_suggtion2_tv.setText(String.format(StringUtils.getResStr(R.string.Gain_1_1f_to_achieve_this_goal), differenceValue, unit));
        }

    }


    private void disTargetWeight() {
        float targetWeight = UserSpUtil.readFloat(Constants.IUser.TARGET_WEIGHT,0);//这个体重是服务器的 单位永远是kg

        if (targetWeight<=0){
            targetWeight = (float) ((idealWeight_max+idealWeight_min)/2.0);
        }


           if (!AppConfig.getInstance().isKgModel()){
               targetWeight=ScaleBaseUtils.lb2kg(targetWeight);
           }
         ViewUtils.setTextViewStr(pager_goal_targetWeight_ed,targetWeight+"");
        disWeightSuggestion2();

    }


    private void setBtClick() {
      
        float target = NumUtils.string2Float(pager_goal_targetWeight_ed.getText().toString().trim());

        if (AppConfig.getInstance().isKgModel()){
            if (target>= AppConfig.KG_MIN&&target<AppConfig.KG_MAX){
                saveTargetWeight(target,true);
            }else {
                ToastUtil.show(String.format(StringUtils.getResStr(R.string.Please_enter_a_reasonable_weight_1_1),AppConfig.KG_MIN,AppConfig.KG_MAX));
            }
        }else {
            if (target>= AppConfig.LB_MIN&&target<AppConfig.LB_MAX){
                saveTargetWeight(target,false);
            }else {
                ToastUtil.show(String.format(StringUtils.getResStr(R.string.Please_enter_a_reasonable_weight_1_1),AppConfig.LB_MIN,AppConfig.LB_MAX));
            }
        }

    }

    private void saveTargetWeight(float target, boolean isKg) {

        float targetWeight2;
        if(isKg){
            targetWeight2=target;
        }else {
            targetWeight2=ScaleBaseUtils.lb2kg(target);
        }
        //  targetWeight2=NumUtils.numBaoLiuWei(targetWeight2,1);//就是服务器上存的永远是千克为单位

        //targetWeight永远以kg的单位上传到服务器

        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId", UserSpUtil.readLong(Constants.IUser.USER_ID));
        paramMap.put("targetWeight",targetWeight2);
        final float finalTargetWeight = targetWeight2;
        TyNetUtil.getInstance().setTargetWeight(this, paramMap, new HttpResponse<OriginalParametersResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, OriginalParametersResponse originalParametersResponse,String s) {
                if (isRequestSuccess){

                    if (originalParametersResponse.resultCode==0){
                        UserSpUtil.writeFloat(Constants.IUser.TARGET_WEIGHT, finalTargetWeight);
                        disTargetWeight();//更新本界面的意思

                        //更新TrendsPager
                        if(getActivity()!=null){
                            ((ScaleMainActivity)getActivity()).trendFragmentUpdateTargetWeight();

                        }
                        ToastUtil.show(R.string.Set_success);

                    }else if (originalParametersResponse.resultCode==110){
                        ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                    } else {
                        ToastUtil.show(R.string.Modify_Failed);
                    }
                }else {
                    ToastUtil.show(R.string.Network_connection_error);
                }
            }
        });
    }


}
